//
//  PersonChangImgViewController.m
//  BusineseStore
//
//  Created by 闪风猫 on 2017/11/15.
//  Copyright © 2017年 TNG. All rights reserved.
//

#import "PersonChangImgViewController.h"

@interface PersonChangImgViewController () <UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIImagePickerControllerDelegate>

@property (strong, nonatomic) UIImageView * img;
@property (strong, nonatomic) UIButton * btn;
@property (strong, nonatomic) NSData * data;

@end

@implementation PersonChangImgViewController

-(UIImageView *)img
{
    if (_img == nil) {
        _img =[[UIImageView alloc]initWithFrame:CGRectMake(WIDTH/2-50, kStatusAndNavBarH+60, 100, 100)];
        _img.contentMode=UIViewContentModeScaleAspectFill;
        _img.layer.cornerRadius=50;
        _img.clipsToBounds = YES;
        _img.userInteractionEnabled = YES;
        [_img addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)]];
    }
    return _img;
}

-(UIButton *)btn
{
    if (_btn == nil) {
        _btn = [[UIButton alloc] initWithFrame:CGRectMake(40, kStatusAndNavBarH + 200, WIDTH-80, 40)];
        _btn.titleLabel.font = font(17);
        [_btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_btn setTitle:@"提交" forState:0];
        _btn.layer.cornerRadius = 4;
        [_btn setBackgroundColor:[UIColor redColor]];
    }
    return _btn;
}

-(void)tap
{
    [self chooseImg];
}

-(void)btnClick:(UIButton *)btn
{
    btn.userInteractionEnabled = NO;
    if (self.data == nil) {
        [SVProgressHUD showErrorWithStatus:@"请选择上传图片"];
        return;
    }
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setValue:SFMgbuserid forKey:@"id"];
    [params setValue:SFMloginname forKey:@"bxrName"];
    WeakSelf;
    btn.userInteractionEnabled = NO;
  
    NSString * url = [BASE_URL stringByAppendingString:@"/rest/appLoginController/updateAppUser"];
    NSString * path = [url stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet];
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"*/*" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:SFMToken forHTTPHeaderField:@"X-AUTH-TOKEN"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html", nil];
    
    [manager POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (weakSelf.data!=nil) {
            [formData appendPartWithFileData:weakSelf.data name:@"headimgurl" fileName:@"headimgurl.jpg" mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * dic = (NSDictionary *)responseObject;
        NSString * codeStr = [NSString stringWithFormat:@"%@",dic[@"respCode"]];
        if ([codeStr isEqualToString:@"0"]) {
            [SVProgressHUD ShowSuccessMessage:@"修改成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                weakSelf.personChangImgBlock(weakSelf.img.image);
                [[NSNotificationCenter defaultCenter] postNotificationName:@"personDidChangeImg" object:nil userInfo:nil];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        }else
        {
            [SVProgressHUD ShowErrorMessage:dic[@"respMsg"]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            btn.userInteractionEnabled = YES;
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            btn.userInteractionEnabled = YES;
        });
        NSSLog(@"error=== %@",error);
    }];
}

#pragma mark -点击添加图片
- (void)chooseImg
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"选择" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    WeakSelf;
    UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = weakSelf;
        [strongSelf presentViewController:picker animated:YES completion:nil];
    }];
    
    UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf takePhoto];
    }];
    
    UIAlertAction * action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alert addAction: action1];
    [alert addAction: action2];
    [alert addAction: action3];
    
    [self presentViewController:alert animated:NO completion:nil];
}

#pragma  mark -开始拍照
-(void)takePhoto
{
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        //        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

#pragma mark -当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        self.img.image = image;
        if (UIImagePNGRepresentation(image) != nil)
        {
            self.data = UIImageJPEGRepresentation([UIImage newTry:image], qualityNum);
        }else
        {
            self.data=UIImageJPEGRepresentation(image, qualityNum);
        }
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    NSLog(@"您取消了选择图片");
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"更换头像";
    [self.view addSubview:self.img];
    [self.view addSubview:self.btn];
    self.img.backgroundColor = SFMRandColor;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
